<template>
  <div class="shade" v-if="isShadeShow" data-aos="fade-left"></div>

  <div class="form" data-aos="fade-left" v-if="isShadeShow">
    <div class="form-title">
      报销登记
    </div>
    <el-scrollbar >
    <div class="leave-form">
      <el-form
          ref="ruleFormRef"
          style="max-width: 60vw"
          :model="bill_form"
          label-width="auto"
          class="demo-ruleForm"
          size="default"
          status-icon
          :rules="ruleFormRule"
      >
        <el-form-item label="报销凭证编号" class="el-form-items" prop="bill_no">
          <el-input v-model="bill_form.bill_no" style="width: 240px" placeholder="请填写报销凭证编号" />
        </el-form-item>
        <el-form-item label="原始单据日期" class="el-form-items" prop="bill_date">
          <el-date-picker
              v-model="bill_form.bill_date"
              type="date"
              placeholder="选择原始单据日期"
              value-format="YYYY-MM-DD"
              @change="changeDate"
          />
        </el-form-item>
        <el-form-item label="入账月份" class="el-form-items"  prop="enter_month">
          <el-select
              v-model="bill_form.enter_month"
              placeholder="选择入账月份"
              style="width: 6vw !important;margin-right: 1vh"
          >
            <el-option
                v-for="option in monthOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联项目" class="el-form-items"  prop="related_pro">
          <el-select
              v-model="bill_form.related_pro"
              placeholder="请选择关联项目"
              style="width: 6vw !important;margin-right: 1vh"
          >
            <el-option
                v-for="option in proOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            />
          </el-select>
        </el-form-item>
        <div class="group">
          <div class="title">
            报销选项
          </div>
          <div class="items">
            <div class="item"  v-for="(item, index) in bill_form.list" :key="index" >
              <el-input v-model="item.sum" style="width: 6.5vw !important;margin-right: 1vh" placeholder="金额(单位:元)" type="number" v-on:blur="totalListener"/>
              <el-select
                  v-model="item.type"
                  placeholder="选择类别"
                  style="width: 6vw !important;margin-right: 1vh"
              >
                <el-option
                    v-for="option in financeTypeOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
              <el-input v-model="item.detail" style="width: 34vw !important;" placeholder="备注信息"/>
              <el-button
                  @click="delItem(index)"
                  type="danger"
                  :icon="Delete"
                  style="width: 2vw !important; margin-left: 2vh;"
              />
            </div>
            <el-button
              @click="addItem"
              type="primary"
              style="width: 5vw !important;margin-top: 1vh;"
            >
              +报销选项
            </el-button>
          </div>
        </div>
        <el-form-item label="总金额(单位:元)" class="el-form-items" prop="total">
          <el-input v-model="bill_form.total_money" style="width: 240px" disabled type="number"/>
        </el-form-item>
        <el-form-item label="附件上传" class="el-form-items upload" style="height:14vh; max-height: 20vh" prop="flow_accessory">
          <el-upload
              v-model:file-list="bill_form.flow_accessory"
              class="upload-demo"
              :action="uploadUrl"
              :on-change="handleFileChange"
              style="height: 12vh;"
              :limit="1"
              :on-exceed="fileOverlow"
              :auto-upload="false"
              name="flow_accessory"
          >
            <div class="content">
              <el-button type="success" style="margin-left: 0vw;">+</el-button>
              <div class="el-upload__tip" style="margin-left: 2vw;margin-right: 2vw;width: 20vw">
                请将所有图片等附件汇总至Word文件统一上传
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" class="el-form-items">
          <el-input v-model="bill_form.details" style="width: 240px" type="textarea"/>
        </el-form-item>
        <el-form-item label="审核人员" class="el-form-items" prop="operator">
          <el-cascader
              v-model="bill_form.operator"
              :options="options"
              :show-all-levels="false"
              @change="handleChange1"
              placeholder="请选择审核人"
          />
        </el-form-item>
        <el-form-item label="抄送人员" class="el-form-items">
          <el-cascader
              v-model="bill_form.copy"
              :options="options"
              :show-all-levels="false"
              @change="handleChange2"
              placeholder="请选择抄送人"
          />
        </el-form-item>
        <div class="btn-box" style="margin-top: 3vh;margin-bottom: 3vh;">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
        </div>
      </el-form>
    </div>
    </el-scrollbar>
  </div>
  <div class="close-btn" @click="closeForm" data-aos="fade-left" v-if="isShadeShow">
    <span>关</span>
    <span>闭</span>
  </div>
</template>

<script setup>
import {ElButton, ElInput, ElForm, ElMessage, ElSelect, ElUpload, ElOption, ElFormItem, ElDatePicker} from "element-plus"
import {onMounted, reactive, ref, watch} from "vue"
import {Delete} from "@element-plus/icons-vue"
import emitter from "@/lib/eventBus"
import {clearObject, createMsg, getTime, hasFinanceEmptyValue} from "@/lib/utils"
import {checkUserByRole, submitFlow} from "@/api"
import {createfin, getBills, getFinHandler} from "@/api/Finance/Bill"
import {get_pro_list} from "@/api/Project"
import axios from "axios"
import {createFinanceApprove} from "@/api/OA/Finance"
import {baseurl} from "@/api/http"

const emit = defineEmits(['reload'])

//遮罩层
const isShadeShow = ref(false)
//级联选择
const options = ref([])
const proOptions = ref([])
//报销表单
let bill_form = reactive({
  bill_no : '',
  bill_date : '',
  enter_month : '',
  copy : [],
  flow_accessory:[],
  list: [
    {
      sum:'',
      type:'',
      detail:''
    },
  ],
  operator:[],
  related_pro:'',
  total_money:'',
  details:''
})

const arr = ref([])

const ruleFormRef = ref()
//报销项type
const financeTypeOptions = [
  {
    value: '0',
    label: '交通费用',
  },{
    value: '1',
    label: '住宿费用',
  },{
    value: '2',
    label: '餐补费用',
  },{
    value: '3',
    label: '招待费用',
  },{
    value: '4',
    label: '汽油费用',
  },{
    value: '5',
    label: '其他费用',
  },
]

//月份选择options
const monthOptions = [
  {
    label:'1月',
    value:1
  },{
    label:'2月',
    value:2
  },{
    label:'3月',
    value:3
  },{
    label:'4月',
    value:4
  },{
    label:'5月',
    value:5
  },{
    label:'6月',
    value:6
  },{
    label:'7月',
    value:7
  },{
    label:'8月',
    value:8
  },{
    label:'9月',
    value:9
  },{
    label:'10月',
    value:10
  },{
    label:'11月',
    value:11
  },{
    label:'12月',
    value:12
  },
]

//表单校验规则
const ruleFormRule = reactive({
  bill_no: [
    { required: true, message: '报销凭证编号不能为空', trigger: 'blur' },
  ],
  bill_date: [
    { required: true, message: '原始单据日期不能为空', trigger: 'blur' },
  ],
  enter_month: [
    { required: true, message: '入账月份不能为空', trigger: 'blur' },
  ],
  operator: [
    { required: true, message: '审核人员不能为空', trigger: 'blur' },
  ],
  flow_accessory:[
    { required: true, message: '附件不能为空', trigger: 'blur' },
  ],
  related_pro:[
    { required: true, message: '关联项目不能为空', trigger: 'blur' },
  ],
  total:[
    { required: true, message: '总金额不能为空', trigger: 'blur' },
  ],
  items:[
    { required: true, message: '总金额不能为空', trigger: 'blur' },
  ]
})

//用户信息
let user_info
//遮罩层
const users = ref([])
//时间戳
let now

//uploadUrl
// const uploadUrl = ref('http://www.lv8.com:8000/createFApprove')
const uploadUrl = `${baseurl}/createFApprove`

onMounted(()=>{
  getUserInfo()
  AOS.init()
  // 监听报销页面的显隐
  emitter.on('showFinance',() => {
    isShadeShow.value = true
  })
  getUserList()
  getPros()
  now = getTime()
})

//获取用户信息
const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}


//获取级联用户列表
const getUserList = async () => {
  try {
    let rolename = []
    let roleUser = []
    const {data:res} = await getFinHandler()
    const values = res.data
    values.forEach(value => {
      let datas = Object.values(value)
      datas.forEach(data => {
        if(typeof data === "string"){
          rolename.push(data)
        } else {
          roleUser.push(data)
        }
      })
    })
    for (let i = 0; i < 2; i++){
      options.value.push({
        label:rolename[i],
        value:null,
        children:[]
      })
      for (let j = 0; j < roleUser[i].length; j++){
        options.value[i].children.push({
              label:roleUser[i][j].user_name,
              value:roleUser[i][j].user_id,
            }
        )
      }
    }
  } catch (e) {
    console.log(e)
  }
}

const getPros = async () => {
  const {data:res} = await get_pro_list()
  if (res.code === 200){
    for (let i = 0; i < res.data.length; i ++){
      proOptions.value.push({
        label:res.data[i].project_name,
        value:res.data[i].project_id,
      })
    }
  }
}

//遮罩层显隐
const show = () => {
  isShadeShow.value = !isShadeShow.value
}

//重置表单
const resetForm = (formEl) => {
  formEl.resetFields()
}

const totalListener = () => {
  let sum1 = 0
  for (let i = 0; i < bill_form.list.length; i++){
    sum1 = sum1 + parseInt(bill_form.list[i].sum)
  }
  bill_form.total_money = sum1
}

//关闭、重置表单
const closeForm = () => {
  bill_form= {
    bill_no : '',
    bill_date : '',
    enter_month : '',
    item : '',
    copy : '',
    flow_accessory:[],
    list: [
      {
        sum:'',
        type:'',
        detail:''
      },
    ],
  }
  isShadeShow.value = false
}

const submitForm = async (formEl) => {
  try {
    console.log(bill_form)
    const check = hasFinanceEmptyValue(bill_form)
    if (bill_form.operator[bill_form.operator.length-1] === '') return createMsg('审核人不能为空','warning',false)
    if (bill_form.copy[bill_form.copy.length-1] === '' && bill_form.copy[0] === '') return createMsg('部门不能作为抄送人','warning',false)
    if (bill_form.operator[bill_form.operator.length-1] === bill_form.copy[bill_form.copy.length-1])  return createMsg('审核人和抄送人不能相同','warning',false)
    if (check) {
      const form = new FormData();
      form.append("uploader", user_info.id);
      form.append("operator", bill_form.operator[bill_form.operator.length-1]);
      form.append("details",bill_form.details );
      form.append("bill_no", bill_form.bill_no);
      form.append("bill_date",bill_form.bill_date );
      form.append("enter_month",bill_form.enter_month );
      form.append("finance_items", JSON.stringify(bill_form.list));
      form.append("total_money", bill_form.total_money);
      form.append("related_project", bill_form.related_pro);
      form.append("flow_accessory", arr.value[0]);
      form.append("copy", bill_form.copy[bill_form.copy.length-1] ? bill_form.copy[bill_form.copy.length-1] : "")
      const {data:res} = await createFinanceApprove(form)
      if (res.code === 200){
        isShadeShow.value = false
        bill_form = clearObject(bill_form)
        emit('reload')
        return createMsg('提交申请成功!','success',true)
      } else if (res.code === 403){
        return createMsg('文件上传失败','error',true)
      } else {
        return createMsg('创建失败','error',true)
      }
    } else {
      console.log(check)
    }
  } catch (error) {
    return createMsg('创建失败','error',true)
  }
}

const handleChange1 = () => {
  // console.log(bill_form.operator[bill_form.operator.length-1])
}

const handleChange2 = () => {
  // console.log(bill_form.copy[bill_form.copy.length-1])
}

const addItem = () => {
  bill_form.list.push({
    sum:'',
    type:'',
    detail:''
  })
}

const delItem = (index) => {
  if(bill_form.list.length === 1){
    return
  }
  bill_form.list.splice(index,1)
}

const changeDate = () => {
}


// 文件状态改变时的钩子，添加文件、上传成功和上传失败时
const handleFileChange = (file) => {
  arr.value.push(file.raw)
}

// 文件数量超过最大显示
const fileOverlow = () => {
  ElMessage({
    message:`只可上传1个文件`,
    type:'warning'
  })
}

const handleChange = () => {
}


defineExpose({
  show
})
</script>

<style scoped lang="less">
.create-box{
  height: 89%;
  width: 18%;
  margin-top: 1.5vh;
  margin-left: 4vw;
  background-color: rgba(250, 250, 250);
  border-radius: 10px;
  box-shadow: 0 0 5px 5px lightgray;
  border: 1px solid lightgray;
  .create_title{
    height: 5vh;
    border-bottom: 1px solid #d6d6d6;
    line-height: 5vh;
    text-align: left;
    padding-left: 1.5vw;
    box-sizing: border-box;
    font-size: 2vh;
    font-weight: 700;
    letter-spacing: 1px;
  }
  .create_body{
    .body_item{
      margin-bottom: 1.5vh;
      .body_title{
        height: 5vh;
        border-bottom: 1px solid #ebebeb;
        text-align: left;
        line-height: 5vh;
        padding-left: 1.5vw;
        font-weight: 600;
        letter-spacing: 1px;
      }
      .items{
        display: flex;
        flex-wrap: wrap;
        .item{
          height: 8vh;
          border-right: 1px solid rgba(245, 245, 245);
          width: 32%;
          border-bottom: 1px solid rgba(245, 245, 245);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          .el-icon{
            margin-bottom: 5px;
            color: rgba(66,133,244);
            font-size: 2.5vh;
          }
          span{
            font-size: 1.5vh;
          }
          &:hover{
            cursor: pointer;
            background-color: #f0f0f0;
          }
        }
      }
    }
  }
}
.shade{
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: 800;
  top: 0vh;
  left: 3vw;
  background-color: rgba(0,0,0,.7);
}
.form{
  position: absolute;
  top: 0vh;
  left: 26vw;
  z-index: 950;
  height: 100vh;
  width: 74vw;
  background-color: white;
  padding: 20px;
  box-sizing: border-box;
  background-color: rgba(250, 250, 250);
  .form-title{
    text-align: left;
    font-size: 2.2vh;
    font-weight: 600;
    letter-spacing: 1px;
    padding-left: 2vh;
    margin-top: 1vh;
  }
  .leave-form{
    margin-top: 1vh;
    max-height: 84vh;
    margin-bottom: 3vh;
    .el-form{
      padding: 2vh;
      .el-form-items{
        width: 69vw;
        border: 1px solid rgba(238, 238, 238);
        margin: 0 !important;
        //background-color: ;
        height: 8vh;
        align-items:center;
        justify-content: center;
        .el-form-item--default .el-form-item__label {
        }
        :deep(.el-form-item__label-wrap) {
          width: 10vw;
          line-height: 8vh;
          height: 8vh;
          text-align: center;
          box-sizing: border-box;
          border-right: 1px solid rgba(238, 238, 238);
          margin-left: 0 !important;
          &:last-child {
            border-right: none;
          }
        }
        :deep(.el-form-item__label){
          padding: 0 !important;
          margin: auto !important;
        }
        :deep(.el-range-editor.el-input__wrapper){
          width: 45vw;
          margin-left: 3vw;
        }
        :deep(.el-input) {
          width: 46vw !important;
          margin-left: 3vw;
        }
        :deep(.el-textarea ){
          width: 46vw !important;
          margin-left: 3vw;
        }
      }
    }
    .group{
      width: 69vw;
      min-height: 10vh;
      display: flex;
      border-right: 1px solid rgba(238, 238, 238);
      border-left:  1px solid rgba(238, 238, 238);
      .title{
        width: 14.6%;
        min-height: 10vh;
        line-height: 8vh;
        border-right: 1px solid rgba(238, 238, 238);
        box-sizing: border-box;
        text-align: center;
        font-size: 1.5vh;
        color: rgb(96, 98, 102);
      }
      .items{
        width: 86%;
        display: flex;
        flex-direction: column;
        padding: 1vh 1vh 1vh 6.5vh;
        box-sizing: border-box;
        justify-content: space-between;
        background-color: #fff;
        .item{
          margin-top: 1vh;
          display: flex;
          justify-content: left;
        }
      }
    }
    .upload-demo{
      height: 6vh;
      width: 30vw;
      display: flex;
      justify-content: left;
      align-items: center;
      :deep(.el-upload-list ){
        //margin: 10px 0 0;
        //padding: 0;
        //list-style: none;
        //position: relative;
        width: 33vw;
      }
      .el-upload-list__item {
        width: 30vw !important;
      }
    }
  }
}
.close-btn{
  position: absolute;
  top: 15vh;
  left: 24vw;
  height: 9vh;
  width: 3.5vw;
  z-index: 899;
  background-color: rgba(255, 87, 34);
  margin: 1vh auto;
  border: 2px solid white;
  box-sizing: border-box;
  border-radius: 5px;
  display: flex;
  justify-content: space-around;
  color: white;
  flex-direction: column;
  padding-left: 0.5vw;
  align-items: start;
  font-size: 1.6vh;
  &:hover{
    cursor: pointer;
  }
}
:deep(.el-form-item--default .el-form-item__content) {
  line-height: 32px;
  height: 8vh;
  background-color: #fff;
}
.upload{
  :deep(.form .leave-form .el-form .el-form-items .el-form-item__label-wrap){
    line-height: 14vh;
    height: 14vh;
  }
  :deep(.el-form-item__content){
    height: 14vh;
  }
}
</style>

